package com.auditlog.format.impl;

import com.auditlog.datasource.db.SqlType;
import com.auditlog.datasource.struct.FieldChangeLog;
import com.auditlog.datasource.struct.RecordImage;
import com.auditlog.datasource.struct.RowChangeLog;
import com.auditlog.datasource.struct.TableRecord;
import com.auditlog.format.AbstractRecordImageFormat;

import java.util.*;

public class InsertRecordImageFormat extends AbstractRecordImageFormat {

    @Override
    public void doFormat(RecordImage recordImage) {
        TableRecord afterRecord = recordImage.getAfterRecord();
        Map<String, List<Object>> after = afterRecord.getRows();
        Set<String> insertedKeys = after.keySet();
        List<List<Object>> insertPks = recordImage.getInsertPks();
        Iterator<List<Object>> iterator = insertPks.iterator();
        while (iterator.hasNext()) {
            List<Object> pkValue = iterator.next();
            String key = DEFAULT_SQL_RUNNER.assembleKey(recordImage.getPkColumnsName(), pkValue, afterRecord.getDelimiter());
            // insert的数据可能被同一批操作删除
            if (!insertedKeys.contains(key)) {
                iterator.remove();
            }
        }
    }

    @Override
    public Map<SqlType, List<RowChangeLog>> changeLog(RecordImage recordImage) throws Exception {
        return this.buildInsertChangeLog(recordImage);
    }

    @Override
    public SqlType getType() {
        return SqlType.INSERT;
    }
}
